/* Copyright (C) 2011 Riccardo Marson

   This file is part of OpenPool, an open-source game of pool. 

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   RICCARDO MARSON BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
   AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  See Readme.rtf for further information.
  
*/

#include "rescache.h"

#include <assert.h>

//---------------------------------------------------------------------------
// Resources and Handles by type
//---------------------------------------------------------------------------

//*** Audio

eResourceType CAudioResHandle::getType()
{
    return RES_SOUND;
}

eResourceType CAudioResource::getType()
{
    return RES_SOUND;
}

ResHandlePtr CAudioResource::getHandle()
{
    return mHandle;
}

bool CAudioResource::load(string resName)
{
    int exist = PHYSFS_exists(resName.c_str());
    
    if (exist == 0)
    {
        string msg = string("Resource Cache Error: Failed to load resource: ") + resName + string(" . File is not present in the search paths.");
        
        CLogManager::getSingleton()->logMessage(msg.c_str());
        return false;
    }
    else
    {
        PHYSFS_file* f = PHYSFS_openRead(resName.c_str());
        
        PHYSFS_sint64 f_size = PHYSFS_fileLength(f);
        
        if (f_size == -1)
        {
            string msg = string("Resource Cache Error: Size could not be determined for resource: ") + resName;
            
            CLogManager::getSingleton()->logMessage(msg.c_str());
            
            PHYSFS_close(f);
            
            return false;

        }
        else
        {
            char *buffer = new char[f_size];
            
            int length_read = PHYSFS_read(f, buffer, 1, f_size);
            
            if (length_read < f_size)
            {
                string msg = string("Resource Cache Error: File was not entirely loaded. ") + resName;
                
                CLogManager::getSingleton()->logMessage(msg.c_str());
                
                PHYSFS_close(f);
                
                delete buffer;
                
                return false;
            }
            else
            {
                PHYSFS_close(f);
                
                //Load Sounds. This will decode and load sounds into memory. Plays quicker at the cost of a little RAM usage.
                //Sounds may also be streamed using sf::SoundStream: less RAM but a small CPU overhead, as sounds must be decoded in realtime.
                //Since only very simple and small sounds are used here, the preferred choice is loading them in memory.

                mHandle = ResHandlePtr( new CAudioResHandle() );
                
                CAudioResHandle* tmpH = dynamic_cast<CAudioResHandle*>(mHandle.get());
                
                bool ok = tmpH->soundBuffer.LoadFromMemory(buffer, f_size);
                
                if (!ok)
                {
                    string msg = string("Resource Cache Error: Could not decode sound: ") + resName;
                    
                    CLogManager::getSingleton()->logMessage(msg.c_str());
                    
                    delete buffer;
                    
                    return false;

                }
                else
                {
                    tmpH->sound.SetBuffer(tmpH->soundBuffer);
                    
                    delete buffer;
                    
                    string msg = "Sound Loaded: " + resName;
                    CLogManager::getSingleton()->logMessage(msg.c_str());

                    return true;
                    
                }
            }
            
        }
        
    }
        
}

bool CAudioResource::unload()
{
	//nothing to be done. sf:: classes clean up after themselves
	return true;
}


//*** Graphics / Textures

eResourceType CImageResHandle::getType()
{
	return RES_TEXTURE;
}

eResourceType  CImageResource::getType()
{
	return RES_TEXTURE;
}

ResHandlePtr CImageResource::getHandle()
{
    return mHandle;
}

bool CImageResource::load(string resName)
{
	int exist = PHYSFS_exists(resName.c_str());

	if (exist == 0)
	{
		string msg = string("Resource Cache Error: Failed to load resource: ") + resName + string(" . File is not present in the search paths.");

		CLogManager::getSingleton()->logMessage(msg.c_str());
		return false;
	}
	else
	{
		PHYSFS_file* f = PHYSFS_openRead(resName.c_str());

		PHYSFS_sint64 f_size = PHYSFS_fileLength(f);

		if (f_size == -1)
		{
			string msg = string("Resource Cache Error: Size could not be determined for resource: ") + resName;

			CLogManager::getSingleton()->logMessage(msg.c_str());

			PHYSFS_close(f);

			return false;

		}
		else
		{
			BYTE *buffer = new BYTE[f_size];

			int length_read = PHYSFS_read(f, buffer, 1, f_size);

			if (length_read < f_size)
			{
				string msg = string("Resource Cache Error: File was not entirely loaded. ") + resName;

				CLogManager::getSingleton()->logMessage(msg.c_str());

				PHYSFS_close(f);

				delete buffer;

				return false;
			}
			else
			{
				PHYSFS_close(f);

				//Load Image and related OpenGL Texture.

				mHandle = ResHandlePtr( new CImageResHandle() );

				CImageResHandle* tmpH = dynamic_cast<CImageResHandle*>(mHandle.get());

				tmpH->glTextureID = loadTexture(resName, f_size, buffer);

				if (tmpH->glTextureID == 0)
				{
					string msg = string("Resource Cache Error: Could not load OpenGL Texture: ") + resName;

					CLogManager::getSingleton()->logMessage(msg.c_str());

					delete buffer;

					return false;

				}
				else
				{
					delete buffer;

					string msg = "Texture Loaded: " + resName;
					CLogManager::getSingleton()->logMessage(msg.c_str());

					return true;

				}
			}

		}

	}
}

GLuint CImageResource::loadTexture(string fileName, PHYSFS_sint64 size, BYTE* buffer)
{
	// Note: Reverted to FreeImage to load textures as sf::Image does not expose GL Texture ID,
	// does not give freedom over texture settings and forces to keep in memory the raw pixel data
	// after texture creation.
	// Might go back to sf::Image when SFML 2.0 is released.

	//image format
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	//pointer to the image, once loaded
	FIBITMAP *dib(0);
	FIBITMAP *img(0);
	//pointer to the image data
	BYTE* bits(0);
	//image width and height
	unsigned int w(0), h(0);

	//check the file signature and deduce its format
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	//if still unknown, try to guess the file format from the file extension
	if(fif == FIF_UNKNOWN)
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	//if still unkown, return failure
	if(fif == FIF_UNKNOWN)
		return 0;

	//check that the plugin has reading capabilities and load the file
	if(FreeImage_FIFSupportsReading(fif))
	{
		FIMEMORY *stream = FreeImage_OpenMemory(buffer, static_cast<DWORD>(size));

		dib = FreeImage_LoadFromMemory(fif, stream);

		FreeImage_CloseMemory(stream);
	}
	//if the image failed to load, return failure
	if(!dib)
		return 0;

	img = FreeImage_ConvertTo32Bits(dib);

	//retrieve the image data
	bits = FreeImage_GetBits(img);
	//get the image width and height
	w = FreeImage_GetWidth(img);
	h = FreeImage_GetHeight(img);

	string msg = "";

	//if this somehow one of these failed (they shouldn't), return failure
	if((bits == 0) || (w == 0) || (h == 0))
	{
		msg = "Error! Texture Not Loaded: ";
		msg += fileName;

		CLogManager::getSingleton()->logMessage(msg.c_str());

		return 0;
	}

	GLuint glTexID = 0;

	glGenTextures(1, &glTexID);
	glBindTexture(GL_TEXTURE_2D, glTexID);

	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
			GL_MODULATE );

	glTexParameteri(GL_TEXTURE_2D,GL_GENERATE_MIPMAP,GL_TRUE);

	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
			GL_LINEAR_MIPMAP_LINEAR );

	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
			GL_LINEAR_MIPMAP_LINEAR );

	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
			GL_REPEAT );

	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
			GL_REPEAT );

	gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, w, h,
			GL_BGRA, GL_UNSIGNED_BYTE, bits );

	//Free FreeImage's copy of the data
	FreeImage_Unload(dib);
	FreeImage_Unload(img);

	return glTexID;

}

bool CImageResource::unload()
{
	CImageResHandle *texH = dynamic_cast<CImageResHandle*>(mHandle.get());

	glDeleteTextures(1, &texH->glTextureID);

	texH->glTextureID = 0;

	return true;
}

//*** Graphics / Obj models

eResourceType CObjResHandle::getType()
{
	return RES_MODEL;
}

const ModelOBJ* CObjResHandle::model()
{
	return &mModel;
}

eResourceType CObjResource::getType()
{
	return RES_MODEL;
}

ResHandlePtr CObjResource::getHandle()
{
	return mHandle;
}

bool CObjResource::load(string resName)
{
	int exist = PHYSFS_exists(resName.c_str());

	if (exist == 0)
	{
		string msg = string("Resource Cache Error: Failed to load resource: ") + resName + string(" . File is not present in the search paths.");

		CLogManager::getSingleton()->logMessage(msg.c_str());
		return false;
	}
	else
	{
		PHYSFS_file* f = PHYSFS_openRead(resName.c_str());

		PHYSFS_sint64 f_size = PHYSFS_fileLength(f);

		if (f_size == -1)
		{
			string msg = string("Resource Cache Error: Size could not be determined for resource: ") + resName;

			CLogManager::getSingleton()->logMessage(msg.c_str());

			PHYSFS_close(f);

			return false;

		}
		else
		{
			char *buffer = new char[f_size];

			int length_read = PHYSFS_read(f, buffer, 1, f_size);

			if (length_read < f_size)
			{
				string msg = string("Resource Cache Error: File was not entirely loaded. ") + resName;

				CLogManager::getSingleton()->logMessage(msg.c_str());

				PHYSFS_close(f);

				delete buffer;

				return false;
			}
			else
			{
				PHYSFS_close(f);

				//Load Wavefront OBJ model

				mHandle = ResHandlePtr( new CObjResHandle() );

				CObjResHandle* tmpH = dynamic_cast<CObjResHandle*>(mHandle.get());

				if (!tmpH->mModel.importFromMemory(buffer))
				{
					string msg = string("Resource Cache Error: Could not load OBJ Model: ") + resName;

					CLogManager::getSingleton()->logMessage(msg.c_str());

					delete buffer;

					return false;

				}
				else
				{
					delete buffer;

					string msg = "OBJ Model Loaded: " + resName;
					CLogManager::getSingleton()->logMessage(msg.c_str());

					return true;

				}
			}

		}

	}
}

bool CObjResource::unload()
{
	//nothing to be done, ModelOBJ cleans after itself
	return true;
}

//---------------------------------------------------------------------------
// Resource Cache
//---------------------------------------------------------------------------

CResourceCache* CResourceCache::uniqueInstance = NULL;

CResourceCache::CResourceCache(const char *argv0)
{
    assert(!uniqueInstance);
    uniqueInstance = this;

    PHYSFS_init(argv0);

    mRunDirectory = string( PHYSFS_getBaseDir() );
    
#if defined (SFML_SYSTEM_MACOS)
    //TODO: move the packaged resources inside the app bundle.
#endif

    string root = "/";

    PHYSFS_mount( mRunDirectory.c_str(), root.c_str(), 1 );

    CLogManager::getSingleton()->logMessage("Resource Cache Initialized.");
}

CResourceCache::~CResourceCache()
{
    assert(uniqueInstance);
    uniqueInstance = NULL;

    PHYSFS_deinit();

    CLogManager::getSingleton()->logMessage("Resource Cache Destroyed.");
}

CResourceCache* CResourceCache::getSingletonPtr()
{
    return uniqueInstance;
}

bool CResourceCache::registerSearchPath(string searchPath)
{
	string root = "/";

	string fullPath = mRunDirectory + "/" + searchPath;

	int ok = PHYSFS_mount(fullPath.c_str(), root.c_str(), 1);

	if (ok == 0)
	{
		string msg = string("Cache Error: Failed to mount search path: ") + searchPath;

		CLogManager::getSingleton()->logMessage(msg.c_str());

		return false;
	}
	else
	{
		mSearchPaths.push_back(searchPath);
		return true;
	}
}

ResHandlePtr CResourceCache::requestResource(string resName, eResourceType resType)
{
    ResPtr tempRes;
    
    // check to see if the requested reource has already been loaded
    // if it is return its handle without loading.
    ResMap::iterator resIter = mResources.find(resName);
    if ( resIter != mResources.end())
    {
    	tempRes = (*resIter).second;
    	return tempRes->getHandle();
    }

    // if the requested resource is not already stored, load it, store it and return the handle.
    switch (resType)
    {
        case RES_SOUND:
        {
            tempRes = ResPtr( new CAudioResource() );
            CAudioResource* audioRes = dynamic_cast<CAudioResource*>(tempRes.get());
            audioRes->load(resName);
            break;
        }
        case RES_MODEL:
        {
        	tempRes = ResPtr( new CObjResource() );
        	CObjResource* objRes = dynamic_cast<CObjResource*>(tempRes.get());
        	objRes->load(resName);
            break;
        }
        case RES_TEXTURE:
        {
        	tempRes = ResPtr( new CImageResource() );
        	CImageResource* imageRes = dynamic_cast<CImageResource*>(tempRes.get());
        	imageRes->load(resName);
            break;
        }
    }
    
    mResources[resName] = tempRes;

    return tempRes->getHandle(); 
}

char* CResourceCache::requestScriptSource(string srcName)
{
	int exist = PHYSFS_exists(srcName.c_str());

	char *buffer = NULL;

	if (exist == 0)
	{
		string msg = string("Resource Cache Error: Failed to load resource: ") + srcName + string(" . File is not present in the search paths.");

		CLogManager::getSingleton()->logMessage(msg.c_str());
		return NULL;
	}
	else
	{
		PHYSFS_file* f = PHYSFS_openRead(srcName.c_str());

		PHYSFS_sint64 f_size = PHYSFS_fileLength(f);

		if (f_size == -1)
		{
			string msg = string("Resource Cache Error: Size could not be determined for resource: ") + srcName;

			CLogManager::getSingleton()->logMessage(msg.c_str());

			PHYSFS_close(f);

			return NULL;

		}
		else
		{
			buffer = new char[f_size];

			int length_read = PHYSFS_read(f, buffer, 1, f_size);

			if (length_read < f_size)
			{
				string msg = string("Resource Cache Error: File was not entirely loaded. ") + srcName;

				CLogManager::getSingleton()->logMessage(msg.c_str());

				PHYSFS_close(f);

				return NULL;
			}
			else
			{
				PHYSFS_close(f);

				return buffer;
			}

		}

	}
}

bool CResourceCache::unloadResource(string resName)
{
	ResMap::iterator resIter = mResources.find(resName);

	if (resIter == mResources.end())
	{
		string msg = "Failed to unload resource: " + resName + " . File not found.";
		CLogManager::getSingleton()->logMessage(msg.c_str());

		return false;
	}
	else
	{
		(*resIter).second->unload();
		mResources.erase(resIter);
		return true;
	}
}

void CResourceCache::unloadAllResources()
{
	for (ResMap::iterator it = mResources.begin(); it != mResources.end(); ++it)
		(*it).second->unload();

	mResources.clear();
}
